<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="视频名称" prop="videoName">
        <el-input
          v-model="queryParams.videoName"
          placeholder="请输入视频名称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 180px"
        />
      </el-form-item>
      <el-form-item label="视频类型" prop="videoType">
        <el-select
          v-model="queryParams.videoType"
          placeholder="选择类型"
          clearable
          style="width: 120px"
        >
          <el-option label="网络视频" value="url" />
          <el-option label="本地文件" value="local" />
          <el-option label="实时流" value="rtmp" />
          <el-option label="循环视频" value="loop" />
        </el-select>
      </el-form-item>
      <el-form-item label="视频状态" prop="videoStatus">
        <el-select
          v-model="queryParams.videoStatus"
          placeholder="选择状态"
          clearable
          style="width: 120px"
        >
          <el-option label="可用" value="active" />
          <el-option label="不可用" value="inactive" />
          <el-option label="测试中" value="testing" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:fishTestVideo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:fishTestVideo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:fishTestVideo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:fishTestVideo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 批量操作工具栏 -->
    <div v-if="selectedVideos.length > 0" style="margin-bottom: 15px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
      <span style="margin-right: 15px;">已选择 {{ selectedVideos.length }} 个视频</span>
      <el-button 
        size="mini" 
        type="danger" 
        @click="handleBatchDelete"
        v-hasPermi="['system:fishTestVideo:remove']"
      >
        批量删除
      </el-button>
      <el-button size="mini" @click="clearSelection">取消选择</el-button>
    </div>

    <!-- 网格视频列表 -->
    <div v-loading="loading" class="video-grid">
      <div 
        v-for="video in fishTestVideoList" 
        :key="video.videoId" 
        class="video-card"
        :class="{ 'selected': isSelected(video.videoId) }"
        @click="toggleSelection(video)"
      >
        <!-- 选择框 -->
        <div class="card-checkbox">
          <el-checkbox 
            :value="isSelected(video.videoId)" 
            @change="toggleSelection(video)"
            @click.stop
          />
        </div>

        <!-- 视频缩略图/预览区 -->
        <div class="video-thumbnail" @click.stop="previewVideo(video)">
          <div v-if="isVideoUrl(video.videoUrl)" class="thumbnail-container">
            <video 
              :src="video.videoUrl" 
              muted
              preload="metadata"
              class="thumbnail-video"
              @error="handleThumbnailError"
            />
            <div class="play-overlay">
              <i class="el-icon-video-play"></i>
            </div>
          </div>
          <div v-else class="thumbnail-placeholder">
            <i class="el-icon-video-camera"></i>
            <p>{{ getVideoTypeText(video.videoType) }}</p>
          </div>
          
          <!-- 时长标识 -->
          <div v-if="video.videoDuration" class="duration-badge">
            {{ formatDuration(video.videoDuration) }}
          </div>
          <div v-else class="duration-badge live">
            LIVE
          </div>
        </div>

        <!-- 视频信息 -->
        <div class="video-info">
          <div class="video-title" :title="video.videoName">
            {{ video.videoName }}
          </div>
          
          <div class="video-meta">
            <div class="meta-row">
              <el-tag :type="getVideoTypeTag(video.videoType)" size="mini">
                {{ getVideoTypeText(video.videoType) }}
              </el-tag>
              <el-tag :type="getVideoStatusTag(video.videoStatus)" size="mini">
                {{ getVideoStatusText(video.videoStatus) }}
              </el-tag>
            </div>
            
            <div class="meta-row">
              <span class="video-id">ID: {{ video.videoId }}</span>
              <span class="video-date">{{ parseTime(video.createTime, '{m}-{d} {h}:{i}') }}</span>
            </div>
          </div>

          <div v-if="video.videoDescription" class="video-description" :title="video.videoDescription">
            {{ video.videoDescription }}
          </div>

          <div class="video-url" :title="video.videoUrl">
            <el-link 
              :href="video.videoUrl" 
              type="primary" 
              target="_blank"
              :underline="false"
              size="mini"
            >
              <i class="el-icon-link"></i> 查看地址
            </el-link>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="video-actions" @click.stop>
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-video-play"
            @click="previewVideo(video)"
            title="预览视频"
          >
            预览
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(video)"
            v-hasPermi="['system:fishTestVideo:edit']"
            title="编辑视频"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(video)"
            v-hasPermi="['system:fishTestVideo:remove']"
            style="color: #f56c6c"
            title="删除视频"
          >
            删除
          </el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && fishTestVideoList.length === 0" class="empty-state">
        <i class="el-icon-video-camera-solid"></i>
        <p>暂无视频数据</p>
        <el-button type="primary" @click="handleAdd">添加第一个视频</el-button>
      </div>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改测试视频管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="视频名称" prop="videoName">
              <el-input v-model="form.videoName" placeholder="请输入视频名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视频类型" prop="videoType">
              <el-select v-model="form.videoType" placeholder="请选择视频类型" style="width: 100%">
                <el-option label="网络视频" value="url" />
                <el-option label="本地文件" value="local" />
                <el-option label="实时流(RTMP)" value="rtmp" />
                <el-option label="循环视频" value="loop" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="视频地址" prop="videoUrl">
              <div style="display: flex; gap: 8px;">
                <el-input 
                  v-model="form.videoUrl" 
                  placeholder="请输入视频URL地址，支持本地路径/网络URL/RTMP流"
                  style="flex: 1"
                />
                <el-button 
                  type="primary" 
                  icon="el-icon-video-play" 
                  @click="testVideoUrl"
                  :disabled="!form.videoUrl"
                >
                  测试
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视频时长(秒)" prop="videoDuration">
              <el-input-number 
                v-model="form.videoDuration" 
                :min="0" 
                :max="86400"
                controls-position="right"
                placeholder="实时流留空"
                style="width: 100%"
              />
              <div style="font-size: 12px; color: #909399; margin-top: 5px;">
                实时流和循环视频可留空
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视频状态" prop="videoStatus">
              <el-select v-model="form.videoStatus" placeholder="请选择视频状态" style="width: 100%">
                <el-option label="可用" value="active" />
                <el-option label="不可用" value="inactive" />
                <el-option label="测试中" value="testing" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="视频描述" prop="videoDescription">
              <el-input 
                v-model="form.videoDescription" 
                type="textarea" 
                :rows="3"
                placeholder="请描述视频内容、来源等信息"
              />
            </el-form-item>
          </el-col>
          <!-- 视频预览区域 -->
          <el-col :span="24" v-if="form.videoUrl && showPreview">
            <el-form-item label="视频预览">
              <div class="video-preview">
                <video 
                  v-if="isVideoUrl(form.videoUrl)" 
                  :src="form.videoUrl" 
                  controls 
                  style="width: 100%; max-height: 300px; border-radius: 4px;"
                  @error="handleVideoError"
                >
                  您的浏览器不支持视频播放
                </video>
                <div v-else style="padding: 20px; text-align: center; background: #f5f7fa; border-radius: 4px;">
                  <i class="el-icon-video-camera" style="font-size: 48px; color: #909399;"></i>
                  <p style="margin: 10px 0 0 0; color: #909399;">
                    {{ getVideoTypeText(form.videoType) }} - 无法预览
                  </p>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 视频预览对话框 - 全屏显示 -->
    <el-dialog 
      title="🎬 视频预览与AI模型测试" 
      :visible.sync="previewVisible" 
      width="95%" 
      top="2vh"
      append-to-body
      :close-on-click-modal="false"
      custom-class="fullscreen-dialog"
    >
      <div v-if="currentVideo">
        <!-- 顶部布局：视频播放 + 基本信息 -->
        <el-row :gutter="20" style="margin-bottom: 15px;">
          <!-- 左侧：视频播放区域 -->
          <el-col :span="14">
            <el-card shadow="never" style="height: 420px;">
              <div slot="header" style="padding: 10px 0; border-bottom: 1px solid #e4e7ed;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <div>
                    <strong style="font-size: 16px;">{{ currentVideo.videoName }}</strong>
                    <el-tag :type="getVideoTypeTag(currentVideo.videoType)" size="mini" style="margin-left: 10px;">
                      {{ getVideoTypeText(currentVideo.videoType) }}
                    </el-tag>
                  </div>
                  <span style="color: #909399; font-size: 12px;">ID: {{ currentVideo.videoId }}</span>
                </div>
              </div>
              
              <video 
                v-if="isVideoUrl(currentVideo.videoUrl)"
                :src="currentVideo.videoUrl" 
                controls 
                autoplay
                style="width: 100%; height: 350px; object-fit: contain; border-radius: 4px;"
                @error="handleVideoError"
              >
                您的浏览器不支持视频播放
              </video>
              <div v-else style="height: 350px; display: flex; align-items: center; justify-content: center; background: #f5f7fa; border-radius: 4px;">
                <div style="text-align: center;">
                  <i class="el-icon-video-camera" style="font-size: 48px; color: #909399;"></i>
                  <p style="margin: 10px 0 0 0; color: #909399;">{{ getVideoTypeText(currentVideo.videoType) }} - 无法预览</p>
                  <p style="margin: 5px 0 0 0; color: #C0C4CC; font-size: 12px;">{{ currentVideo.videoUrl }}</p>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <!-- 右侧：检测统计信息 -->
          <el-col :span="10">
            <el-card shadow="never" style="height: 420px;">
              <div slot="header" style="padding: 10px 0;">
                <div style="display: flex; align-items: center;">
                  <i class="el-icon-data-analysis" style="color: #409eff; margin-right: 5px;"></i>
                  <strong>实时检测统计</strong>
                </div>
              </div>
              
              <!-- 统计数字 -->
              <div v-if="testResult" class="stats-grid">
                <div class="stat-item">
                  <div class="stat-number">{{ testResult.fishCount || 0 }}</div>
                  <div class="stat-label">检测到鱼类</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">{{ testResult.processingTime || 0 }}ms</div>
                  <div class="stat-label">处理时间</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">{{ testResult.avgConfidence || 0 }}%</div>
                  <div class="stat-label">平均置信度</div>
                </div>
              </div>
              
              <!-- 加载状态或空状态 -->
              <div v-else-if="testLoading" style="text-align: center; padding: 40px 0;">
                <el-progress 
                  :percentage="testProgress" 
                  :stroke-width="6"
                  status="success"
                />
                <p style="margin-top: 15px; color: #606266; font-size: 14px;">{{ testStatusText }}</p>
              </div>
              
              <div v-else style="text-align: center; padding: 60px 0; color: #909399;">
                <i class="el-icon-cpu" style="font-size: 48px; margin-bottom: 15px;"></i>
                <p>等待开始检测...</p>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 模型选择和控制区域 -->
        <el-card shadow="never" style="margin-bottom: 15px;">
          <div slot="header" style="padding: 8px 0;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <div style="display: flex; align-items: center;">
                <i class="el-icon-cpu" style="color: #409eff; margin-right: 5px;"></i>
                <strong>AI检测模型配置</strong>
              </div>
              <el-button 
                size="mini" 
                type="text" 
                icon="el-icon-refresh" 
                @click="loadDetectionModels"
                :loading="modelsLoading"
              >
                刷新模型
              </el-button>
            </div>
          </div>

          <!-- 模型选择表单 -->
          <el-form v-if="!modelsLoading && detectionModels.length > 0" :inline="true" label-width="90px" style="margin-bottom: 0;">
            <el-form-item label="检测模型" style="margin-bottom: 10px;">
              <el-select 
                v-model="selectedModelId" 
                placeholder="选择AI模型"
                style="width: 280px"
                @change="handleModelChange"
                filterable
              >
                <el-option
                  v-for="model in detectionModels"
                  :key="model.modelId"
                  :label="model.modelName"
                  :value="model.modelId"
                  :disabled="model.isActive !== '1'"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>{{ model.modelName }}</span>
                    <el-tag :type="getModelTypeTag(model.modelType)" size="mini">
                      {{ getModelTypeText(model.modelType) }}
                    </el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="置信度" style="margin-bottom: 10px;">
              <el-input-number 
                v-model="testConfidence" 
                :min="0.1" 
                :max="1" 
                :step="0.01"
                :precision="2"
                controls-position="right"
                style="width: 120px"
              />
            </el-form-item>
            
            <el-form-item style="margin-bottom: 10px;">
              <el-button 
                type="primary" 
                size="small"
                :loading="testLoading"
                :disabled="!selectedModelId || !currentVideo"
                @click="startModelTest"
                icon="el-icon-cpu"
              >
                {{ testLoading ? '检测中...' : '开始检测' }}
              </el-button>
              <el-button 
                v-if="testLoading"
                size="small"
                @click="stopModelTest"
                icon="el-icon-close"
              >
                停止
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 选中模型信息 -->
          <div v-if="selectedModel" style="padding: 10px; background: #f8f9fa; border-radius: 4px; font-size: 12px;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span><strong>{{ selectedModel.modelName }}</strong> - {{ selectedModel.modelDescription }}</span>
              <span style="color: #909399;">准确率: {{ selectedModel.accuracyRate }}% | 支持: {{ getSupportSpeciesList(selectedModel.supportSpecies).join(', ') }}</span>
            </div>
          </div>

          <!-- 加载状态和错误提示 -->
          <div v-if="modelsLoading" style="text-align: center; padding: 15px; color: #909399;">
            <i class="el-icon-loading"></i> 正在加载检测模型...
          </div>
          
          <div v-if="!modelsLoading && detectionModels.length === 0" style="padding: 15px;">
            <el-alert
              title="暂无可用检测模型"
              description="请先在鱼类检测模型管理中添加模型，或检查模型是否已启用"
              type="warning"
              show-icon
              :closable="false">
            </el-alert>
          </div>
        </el-card>

        <!-- 检测详情展示区域 -->
        <div v-if="testResult" class="detection-results-container">
          <el-card shadow="never">
            <div slot="header" style="padding: 8px 0;">
              <div style="display: flex; align-items: center;">
                <i class="el-icon-collection-tag" style="color: #67c23a; margin-right: 5px;"></i>
                <strong>检测详情 ({{ testResult.fishCount || 0 }}条鱼类)</strong>
              </div>
            </div>
            
            <!-- 调试信息 -->
            <div style="margin-bottom: 10px; padding: 8px; background: #f0f9ff; border: 1px solid #e0f2fe; border-radius: 4px; font-size: 12px; color: #0369a1;">
              <strong>🔍 调试信息:</strong><br/>
              testResult存在: {{ !!testResult }}<br/>
              testResult.detections存在: {{ !!(testResult && testResult.detections) }}<br/>
              detections长度: {{ testResult && testResult.detections ? testResult.detections.length : 'undefined' }}<br/>
              完整testResult: {{ JSON.stringify(testResult, null, 2) }}
            </div>
            
            <!-- 检测结果网格布局 -->
            <div v-if="testResult.detections && testResult.detections.length > 0" class="detections-grid">
              <div 
                v-for="(detection, index) in testResult.detections" 
                :key="index"
                class="detection-card"
              >
                <!-- 卡片头部：物种和置信度 -->
                <div class="detection-card-header">
                  <div class="species-tags">
                    <el-tag :type="getSpeciesTag(detection.species)" size="small">
                      {{ detection.species }}
                    </el-tag>
                    <el-tag v-if="detection.speciesCategory" type="info" size="mini">
                      {{ detection.speciesCategory }}
                    </el-tag>
                  </div>
                  <div class="confidence-badge">
                    <span class="confidence-value">{{ detection.confidence }}%</span>
                    <el-tag :type="getConfidenceLevelTag(detection.confidenceLevel)" size="mini">
                      {{ detection.confidenceLevel }}
                    </el-tag>
                  </div>
                </div>

                <!-- 位置信息 -->
                <div class="info-section">
                  <div class="info-title">📍 位置信息</div>
                  <div class="info-content">
                    <span>坐标: ({{ detection.x }}, {{ detection.y }})</span>
                    <span>尺寸: {{ detection.width }}×{{ detection.height }}px</span>
                    <span v-if="detection.area">面积: {{ detection.area }}px²</span>
                  </div>
                </div>

                <!-- 尺寸测量 -->
                <div v-if="detection.estimatedLength" class="info-section">
                  <div class="info-title">📏 尺寸测量</div>
                  <div class="measurement-data">
                    <div class="measurement-row">
                      <span class="measure-label">体长:</span>
                      <span class="measure-value primary">{{ detection.estimatedLength }}</span>
                      <span class="measure-label">体高:</span>
                      <span class="measure-value success">{{ detection.estimatedHeight }}</span>
                    </div>
                    <div class="measurement-row">
                      <span class="measure-label">体重:</span>
                      <span class="measure-value warning">{{ detection.estimatedWeight }}</span>
                      <span class="measure-label">比例:</span>
                      <span class="measure-value">{{ detection.aspectRatio }}</span>
                    </div>
                  </div>
                </div>

                <!-- 生物分析 -->
                <div v-if="detection.conditionFactor || detection.estimatedAge" class="info-section">
                  <div class="info-title">🧬 生物分析</div>
                  <div class="bio-data">
                    <div v-if="detection.conditionFactor" class="bio-item">
                      <span>体况:</span>
                      <el-tag :type="getConditionFactorTag(detection.conditionFactor)" size="mini">
                        {{ getConditionFactorText(detection.conditionFactor) }}
                      </el-tag>
                      <span>({{ detection.conditionFactor }})</span>
                    </div>
                    <div v-if="detection.estimatedAge" class="bio-item">
                      <span>年龄:</span>
                      <strong class="age-value">{{ detection.estimatedAge }}</strong>
                    </div>
                    <div v-if="detection.maxSwimSpeed" class="bio-item">
                      <span>游速:</span>
                      <span>{{ detection.maxSwimSpeed }}</span>
                    </div>
                  </div>
                </div>

                <!-- 运动状态 -->
                <div v-if="detection.orientation || detection.activity" class="info-section">
                  <div class="info-title">🏃 运动状态</div>
                  <div class="motion-data">
                    <span v-if="detection.activity" class="motion-item">{{ detection.activity }}</span>
                    <span v-if="detection.direction" class="motion-item">{{ detection.direction }}</span>
                    <span v-if="detection.estimatedSpeed" class="motion-item">{{ detection.estimatedSpeed }}</span>
                  </div>
                </div>

                <!-- 卡片底部：质量评分 -->
                <div class="detection-card-footer">
                  <el-tag :type="getQualityTag(detection.detectionQuality)" size="mini">
                    {{ detection.detectionQuality }}
                  </el-tag>
                  <span v-if="detection.sizeConfidence" style="margin-left: 8px;">
                    <el-tag :type="getSizeConfidenceTag(detection.sizeConfidence)" size="mini">
                      {{ detection.sizeConfidence }}
                    </el-tag>
                  </span>
                  <span v-if="detection.frameId" class="frame-id">#{{ detection.frameId }}</span>
                </div>
              </div>
            </div>
            
            <div v-else style="text-align: center; color: #909399; padding: 40px;">
              <i class="el-icon-search" style="font-size: 48px; margin-bottom: 15px;"></i>
              <p>未检测到鱼类</p>
            </div>
          </el-card>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFishTestVideo, getFishTestVideo, delFishTestVideo, addFishTestVideo, updateFishTestVideo, testFishDetection, stopFishDetection } from "@/api/system/fishTestVideo";
import { listFishDetectionModel } from "@/api/system/fishDetectionModel";

export default {
  name: "FishTestVideo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的视频列表（网格模式）
      selectedVideos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试视频管理表格数据
      fishTestVideoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示预览
      showPreview: false,
      // 视频预览对话框
      previewVisible: false,
      // 当前预览视频
      currentVideo: null,
      // 检测模型相关数据
      detectionModels: [],
      modelsLoading: false,
      selectedModelId: null,
      selectedModel: null,
      testConfidence: 0.5,
      // 测试相关状态
      testLoading: false,
      testProgress: 0,
      testStatusText: '准备开始检测...',
      testResult: null,
      testTimer: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        videoName: null,
        videoUrl: null,
        videoType: null,
        videoDuration: null,
        videoStatus: null,
        videoDescription: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        videoName: [
          { required: true, message: "视频名称不能为空", trigger: "blur" }
        ],
        videoUrl: [
          { required: true, message: "视频地址不能为空", trigger: "blur" }
        ],
        videoType: [
          { required: true, message: "视频类型不能为空", trigger: "change" }
        ],
        videoStatus: [
          { required: true, message: "视频状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询测试视频管理列表 */
    getList() {
      this.loading = true;
      listFishTestVideo(this.queryParams).then(response => {
        this.fishTestVideoList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 清除选择状态
        this.clearSelection();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        videoId: null,
        videoName: null,
        videoUrl: null,
        videoType: 'url',
        videoDuration: null,
        videoStatus: 'active',
        videoDescription: null,
        createTime: null,
        updateTime: null
      };
      this.showPreview = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据（兼容表格模式）
    handleSelectionChange(selection) {
      if (selection && Array.isArray(selection)) {
        this.ids = selection.map(item => item.videoId);
        this.selectedVideos = [...this.ids];
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加测试视频管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const videoId = row.videoId || this.ids
      getFishTestVideo(videoId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改测试视频管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.videoId != null) {
            updateFishTestVideo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFishTestVideo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const videoIds = row.videoId || this.ids;
      this.$modal.confirm('是否确认删除测试视频管理编号为"' + videoIds + '"的数据项？').then(function() {
        return delFishTestVideo(videoIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/fishTestVideo/export', {
        ...this.queryParams
      }, `fishTestVideo_${new Date().getTime()}.xlsx`)
    },
    // 获取视频类型标签样式
    getVideoTypeTag(type) {
      const tagTypes = {
        'url': 'primary',
        'local': 'success',
        'rtmp': 'warning',
        'loop': 'info'
      };
      return tagTypes[type] || 'info';
    },
    // 获取视频类型显示文本
    getVideoTypeText(type) {
      const texts = {
        'url': '网络视频',
        'local': '本地文件',
        'rtmp': '实时流',
        'loop': '循环视频'
      };
      return texts[type] || type;
    },
    // 获取视频状态标签样式
    getVideoStatusTag(status) {
      const tagTypes = {
        'active': 'success',
        'inactive': 'danger',
        'testing': 'warning'
      };
      return tagTypes[status] || 'info';
    },
    // 获取视频状态显示文本
    getVideoStatusText(status) {
      const texts = {
        'active': '可用',
        'inactive': '不可用',
        'testing': '测试中'
      };
      return texts[status] || status;
    },
    // 判断是否为视频URL
    isVideoUrl(url) {
      if (!url) return false;
      // 检查是否为HTTP/HTTPS的视频文件
      const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv'];
      const lowerUrl = url.toLowerCase();
      return (lowerUrl.startsWith('http://') || lowerUrl.startsWith('https://')) && 
             videoExtensions.some(ext => lowerUrl.includes(ext));
    },
    // 预览视频
    previewVideo(row) {
      this.currentVideo = row;
      this.previewVisible = true;
      // 加载检测模型列表
      this.loadDetectionModels();
      // 重置测试状态
      this.resetTestState();
    },
    // 测试视频URL
    testVideoUrl() {
      if (!this.form.videoUrl) {
        this.$modal.msgWarning("请先输入视频地址");
        return;
      }
      
      this.showPreview = true;
      this.$nextTick(() => {
        if (this.isVideoUrl(this.form.videoUrl)) {
          this.$modal.msgSuccess("视频地址格式正确，可以预览");
        } else {
          this.$modal.msgInfo("视频地址已设置，但无法预览（可能是本地文件或RTMP流）");
        }
      });
    },
    // 视频播放错误处理
    handleVideoError(event) {
      console.error('视频加载失败:', event);
      this.$modal.msgError("视频加载失败，请检查视频地址是否正确");
    },
    // 时间格式化
    parseTime(time, pattern) {
      if (!time) return '';
      
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
      let date = new Date(time);
      
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        if (key === 'a') {
          return ['日', '一', '二', '三', '四', '五', '六'][value];
        }
        return value.toString().padStart(2, '0');
      });
      
      return time_str;
    },
    // 网格布局相关方法
    // 检查视频是否被选中
    isSelected(videoId) {
      return this.selectedVideos.includes(videoId);
    },
    // 切换视频选择状态
    toggleSelection(video) {
      const index = this.selectedVideos.indexOf(video.videoId);
      if (index > -1) {
        this.selectedVideos.splice(index, 1);
      } else {
        this.selectedVideos.push(video.videoId);
      }
      this.updateSelectionState();
    },
    // 清除所有选择
    clearSelection() {
      this.selectedVideos = [];
      this.ids = [];
      this.single = true;
      this.multiple = true;
    },
    // 更新选择状态
    updateSelectionState() {
      this.ids = this.selectedVideos;
      this.single = this.selectedVideos.length !== 1;
      this.multiple = this.selectedVideos.length === 0;
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedVideos.length === 0) {
        this.$modal.msgWarning("请先选择要删除的视频");
        return;
      }
      
      this.$modal.confirm(`是否确认删除选中的 ${this.selectedVideos.length} 个视频？`).then(() => {
        return delFishTestVideo(this.selectedVideos.join(','));
      }).then(() => {
        this.getList();
        this.clearSelection();
        this.$modal.msgSuccess("批量删除成功");
      }).catch(() => {});
    },
    // 格式化视频时长
    formatDuration(seconds) {
      if (!seconds) return '0s';
      
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      
      if (hours > 0) {
        return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
      } else if (minutes > 0) {
        return `${minutes}:${secs.toString().padStart(2, '0')}`;
      } else {
        return `${secs}s`;
      }
    },
    // 缩略图加载错误处理
    handleThumbnailError(event) {
      // 缩略图加载失败时的处理，可以设置默认图片或隐藏
      console.log('缩略图加载失败:', event);
    },
    // 模型测试相关方法
    // 加载检测模型列表
    loadDetectionModels() {
      this.modelsLoading = true;
      console.log('🚀 开始加载检测模型列表...');
      
      // 重置数据
      this.detectionModels = [];
      this.selectedModelId = null;
      this.selectedModel = null;
      
      const params = { 
        pageNum: 1,
        pageSize: 100
      };
      
      console.log('📤 请求参数:', params);
      console.log('📡 请求URL: /system/fishDetectionModel/list');
      
      listFishDetectionModel(params).then(response => {
        console.log('📥 模型列表响应:', response);
        
        if (response && response.code === 200) {
          this.detectionModels = response.rows || [];
          console.log('✅ 成功加载模型列表:', this.detectionModels.length, '个模型');
          console.log('📋 模型详情:', this.detectionModels);
          
          if (this.detectionModels.length === 0) {
            this.$modal.msgWarning("暂无检测模型数据，请检查：\n1. 数据库是否执行了初始化脚本\n2. 鱼类检测模型管理中是否有数据");
          } else {
            this.$modal.msgSuccess(`成功加载 ${this.detectionModels.length} 个检测模型`);
          }
        } else {
          console.error('❌ 模型列表响应错误:', response);
          let errorMsg = "响应格式错误";
          if (response && response.msg) {
            errorMsg = response.msg;
          } else if (response && response.message) {
            errorMsg = response.message;
          }
          this.$modal.msgError("加载模型列表失败: " + errorMsg);
        }
        
        this.modelsLoading = false;
      }).catch(error => {
        console.error('💥 加载模型列表网络错误:', error);
        console.error('📍 错误详情:', {
          message: error.message,
          status: error.status,
          statusText: error.statusText,
          response: error.response
        });
        
        this.modelsLoading = false;
        
        let errorMsg = "网络错误";
        if (error.response) {
          if (error.response.status === 403) {
            errorMsg = "权限不足，请检查是否有访问鱼类检测模型的权限";
          } else if (error.response.status === 404) {
            errorMsg = "接口不存在，请检查后端服务是否正常";
          } else if (error.response.status === 500) {
            errorMsg = "服务器内部错误，请检查后端日志";
          } else {
            errorMsg = `HTTP ${error.response.status}: ${error.response.statusText}`;
          }
        } else if (error.message) {
          errorMsg = error.message;
        }
        
        this.$modal.msgError("加载模型列表失败: " + errorMsg + "\n请打开浏览器开发者工具查看详细错误信息");
      });
    },
    // 模型选择变更
    handleModelChange(modelId) {
      this.selectedModel = this.detectionModels.find(model => model.modelId === modelId);
      if (this.selectedModel && this.selectedModel.confidenceThreshold) {
        this.testConfidence = parseFloat(this.selectedModel.confidenceThreshold);
      }
    },
    // 重置测试状态
    resetTestState() {
      this.selectedModelId = null;
      this.selectedModel = null;
      this.testConfidence = 0.5;
      this.testLoading = false;
      this.testProgress = 0;
      this.testStatusText = '准备开始检测...';
      this.testResult = null;
      if (this.testTimer) {
        clearInterval(this.testTimer);
        this.testTimer = null;
      }
    },
    // 开始模型测试
    startModelTest() {
      if (!this.selectedModelId || !this.currentVideo) {
        this.$modal.msgWarning("请选择检测模型和视频");
        return;
      }

      this.testLoading = true;
      this.testProgress = 0;
      this.testResult = null;
      this.testStatusText = '正在初始化模型...';

      // 模拟进度更新
      this.startProgressSimulation();

      // 调用检测API
      const testData = {
        videoId: this.currentVideo.videoId,
        modelId: this.selectedModelId,
        confidenceThreshold: this.testConfidence
      };

      // 这里需要调用后端API
      this.callDetectionAPI(testData);
    },
    // 调用检测API
    callDetectionAPI(testData) {
      testFishDetection(testData).then(response => {
        console.log('🐟 检测API响应:', response);
        console.log('📊 响应数据结构:', {
          code: response.code,
          data: response.data,
          hasData: !!response.data,
          fishCount: response.data?.fishCount,
          detections: response.data?.detections,
          detectionsLength: response.data?.detections?.length
        });
        
        if (response.code === 200) {
          this.testResult = response.data;
          
          // 调试输出
          console.log('✅ 设置testResult:', this.testResult);
          console.log('🔍 testResult.detections:', this.testResult.detections);
          console.log('📈 检测结果数量:', this.testResult.detections?.length);
          
          // 强制Vue重新渲染
          this.$forceUpdate();
          
          this.testLoading = false;
          this.testProgress = 100;
          this.testStatusText = '检测完成';
          this.$modal.msgSuccess(`鱼类检测完成！检测到 ${this.testResult.fishCount} 条鱼类`);
        } else {
          this.testLoading = false;
          this.$modal.msgError("检测失败: " + response.msg);
        }
        
        if (this.testTimer) {
          clearInterval(this.testTimer);
          this.testTimer = null;
        }
      }).catch(error => {
        console.error('检测失败:', error);
        this.testLoading = false;
        this.$modal.msgError("检测失败: " + (error.msg || error.message || '网络错误'));
        if (this.testTimer) {
          clearInterval(this.testTimer);
          this.testTimer = null;
        }
      });
    },
    // 停止模型测试
    stopModelTest() {
      if (this.currentVideo && this.currentVideo.videoId) {
        stopFishDetection(this.currentVideo.videoId).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("检测任务已停止");
          }
        }).catch(error => {
          console.error('停止检测失败:', error);
        });
      }
      
      this.testLoading = false;
      this.testStatusText = '检测已停止';
      if (this.testTimer) {
        clearInterval(this.testTimer);
        this.testTimer = null;
      }
    },
    // 开始进度模拟
    startProgressSimulation() {
      this.testProgress = 0;
      const stages = [
        { progress: 10, text: '正在下载模型...' },
        { progress: 30, text: '模型加载中...' },
        { progress: 50, text: '正在处理视频...' },
        { progress: 70, text: '执行鱼类检测...' },
        { progress: 90, text: '生成检测结果...' },
        { progress: 100, text: '检测完成' }
      ];

      let currentStage = 0;
      this.testTimer = setInterval(() => {
        if (currentStage < stages.length && this.testLoading) {
          const stage = stages[currentStage];
          this.testProgress = stage.progress;
          this.testStatusText = stage.text;
          currentStage++;
        } else {
          clearInterval(this.testTimer);
          this.testTimer = null;
        }
      }, 500);
    },
    // 获取物种标签样式
    getSpeciesTag(species) {
      const tagTypes = {
        'salmon': 'success',
        'trout': 'primary',
        'bass': 'warning',
        'tuna': 'danger',
        'fish': 'info',
        'carp': 'success',
        'cod': 'primary'
      };
      return tagTypes[species] || 'info';
    },
    // 兼容已有的模型类型方法（为了在模型选择中复用）
    getModelTypeTag(type) {
      const tagTypes = {
        'yolo': 'primary',
        'rcnn': 'success', 
        'mobile': 'warning',
        'custom': 'info'
      };
      return tagTypes[type] || 'info';
    },
    getModelTypeText(type) {
      const texts = {
        'yolo': 'YOLO',
        'rcnn': 'R-CNN',
        'mobile': '移动端',
        'custom': '自定义'
      };
      return texts[type] || type;
    },
    // 解析支持物种列表
    getSupportSpeciesList(supportSpecies) {
      if (!supportSpecies) return [];
      
      try {
        // 如果是JSON字符串，解析它
        if (typeof supportSpecies === 'string') {
          const parsed = JSON.parse(supportSpecies);
          if (Array.isArray(parsed)) {
            return parsed;
          }
          // 如果是逗号分隔的字符串
          return supportSpecies.split(',').map(item => item.trim()).filter(item => item);
        }
        // 如果已经是数组
        if (Array.isArray(supportSpecies)) {
          return supportSpecies;
        }
        return [];
      } catch (error) {
        console.warn('解析支持物种列表失败:', error, supportSpecies);
        // 作为逗号分隔的字符串处理
        if (typeof supportSpecies === 'string') {
          return supportSpecies.split(',').map(item => item.trim()).filter(item => item);
        }
        return [];
      }
    },
    // 获取置信度等级标签样式
    getConfidenceLevelTag(level) {
      const tagTypes = {
        '极高': 'success',
        '高': 'primary',
        '中等': 'warning',
        '一般': 'info',
        '较低': 'danger'
      };
      return tagTypes[level] || 'info';
    },
    // 获取健康状态标签样式
    getHealthStatusTag(status) {
      const tagTypes = {
        '健康': 'success',
        '良好': 'primary',
        '一般': 'warning',
        '需关注': 'danger'
      };
      return tagTypes[status] || 'info';
    },
    // 获取检测质量标签样式
    getQualityTag(quality) {
      const tagTypes = {
        '优秀': 'success',
        '良好': 'primary',
        '一般': 'warning',
        '需优化': 'danger'
      };
      return tagTypes[quality] || 'info';
    },
    // 获取体况指数标签样式
    getConditionFactorTag(factor) {
      const value = parseFloat(factor);
      if (value >= 1.5 && value <= 2.0) return 'success'; // 健康
      if (value >= 1.2 && value < 1.5) return 'primary';  // 良好
      if (value >= 1.0 && value < 1.2) return 'warning';  // 偏瘦
      if (value >= 0.8 && value < 1.0) return 'danger';   // 瘦弱
      return 'info'; // 其他
    },
    // 获取体况指数文本描述
    getConditionFactorText(factor) {
      const value = parseFloat(factor);
      if (value >= 1.5 && value <= 2.0) return '健康';
      if (value >= 1.2 && value < 1.5) return '良好';
      if (value >= 1.0 && value < 1.2) return '偏瘦';
      if (value >= 0.8 && value < 1.0) return '瘦弱';
      if (value > 2.0) return '肥胖';
      return '异常';
    },
    // 获取尺寸检测置信度标签样式
    getSizeConfidenceTag(confidence) {
      const tagTypes = {
        '极高精度': 'success',
        '高精度': 'primary',
        '较高精度': 'warning',
        '中等精度': 'info',
        '基础精度': 'danger'
      };
      return tagTypes[confidence] || 'info';
    }
  }
};
</script>

<style scoped>
/* 网格布局样式 */
.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  padding: 0;
  min-height: 200px;
}

/* 视频卡片样式 */
.video-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

.video-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.video-card.selected {
  border: 2px solid #409eff;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);
}

/* 选择框样式 */
.card-checkbox {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  padding: 4px;
}

/* 缩略图样式 */
.video-thumbnail {
  position: relative;
  width: 100%;
  height: 180px;
  overflow: hidden;
  background: #f5f7fa;
  cursor: pointer;
}

.thumbnail-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.thumbnail-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
}

.thumbnail-placeholder i {
  font-size: 48px;
  margin-bottom: 10px;
}

.thumbnail-placeholder p {
  margin: 0;
  font-size: 14px;
}

/* 播放覆盖层 */
.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.video-thumbnail:hover .play-overlay {
  opacity: 1;
}

.play-overlay i {
  font-size: 48px;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

/* 时长标识 */
.duration-badge {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.duration-badge.live {
  background: #f56c6c;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

/* 视频信息样式 */
.video-info {
  padding: 15px;
  flex: 1;
}

.video-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.video-meta {
  margin-bottom: 10px;
}

.meta-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.meta-row:last-child {
  margin-bottom: 0;
}

.video-id, .video-date {
  font-size: 12px;
  color: #909399;
}

.video-description {
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.video-url {
  margin-bottom: 10px;
}

/* 操作按钮样式 */
.video-actions {
  padding: 10px 15px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

/* 空状态样式 */
.empty-state {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
  background: #fafbfc;
  border-radius: 8px;
  border: 2px dashed #e4e7ed;
}

.empty-state i {
  font-size: 64px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-state p {
  font-size: 16px;
  margin: 0 0 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 15px;
  }
  
  .video-card {
    margin-bottom: 0;
  }
}

@media (max-width: 480px) {
  .video-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .video-thumbnail {
    height: 160px;
  }
}

/* 标签间距调整 */
.meta-row .el-tag {
  margin-right: 5px;
}

.meta-row .el-tag:last-child {
  margin-right: 0;
}

/* 旧的测试结果样式已移除，使用新的卡片网格布局 */

/* 移除旧的检测详情样式，已使用新的网格布局样式替代 */

/* 全屏对话框样式 */
.fullscreen-dialog {
  margin: 0 !important;
}

.fullscreen-dialog .el-dialog {
  margin: 2vh auto !important;
  max-height: 96vh !important;
  display: flex !important;
  flex-direction: column !important;
}

.fullscreen-dialog .el-dialog__body {
  flex: 1 !important;
  overflow-y: auto !important;
  padding: 15px 20px !important;
}

/* 统计数字显示 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  border: 1px solid #dee2e6;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  line-height: 1;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #666;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

/* 检测结果网格布局 */
.detections-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 15px;
  padding: 0;
}

.detection-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  transition: all 0.3s ease;
}

.detection-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.detection-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.species-tags {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.confidence-badge {
  display: flex;
  align-items: center;
  gap: 5px;
}

.confidence-value {
  font-weight: bold;
  color: #409eff;
  font-size: 14px;
}

.info-section {
  margin-bottom: 10px;
}

.info-title {
  font-size: 12px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 6px;
  display: flex;
  align-items: center;
}

.info-content {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  font-size: 11px;
  color: #606266;
}

.info-content span {
  background: #f8f9fa;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #e9ecef;
}

/* 尺寸测量数据 */
.measurement-data {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.measurement-row {
  display: grid;
  grid-template-columns: auto 1fr auto 1fr;
  gap: 6px;
  align-items: center;
}

.measure-label {
  font-size: 11px;
  color: #909399;
  text-align: right;
}

.measure-value {
  font-size: 12px;
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 3px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
}

.measure-value.primary {
  color: #409eff;
  background: #ecf5ff;
  border-color: #d9ecff;
}

.measure-value.success {
  color: #67c23a;
  background: #f0f9ff;
  border-color: #e1f3d8;
}

.measure-value.warning {
  color: #e6a23c;
  background: #fdf6ec;
  border-color: #faecd8;
}

/* 生物数据 */
.bio-data {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.bio-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 11px;
  padding: 3px 0;
}

.age-value {
  color: #f56c6c;
  font-size: 12px;
}

/* 运动数据 */
.motion-data {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.motion-item {
  font-size: 11px;
  background: #f8f9fa;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #e9ecef;
  color: #606266;
}

.detection-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.frame-id {
  font-size: 10px;
  color: #c0c4cc;
  font-weight: normal;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .detections-grid {
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .fullscreen-dialog .el-dialog {
    width: 98% !important;
    margin: 1vh auto !important;
    max-height: 98vh !important;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
    gap: 10px;
    padding: 15px 0;
  }
  
  .detections-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .detection-card {
    padding: 10px;
  }
  
  .measurement-row {
    grid-template-columns: 1fr 1fr;
    gap: 4px;
  }
  
  .detection-card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>
